package com.dongge.Test;

import com.dongge.Entity.User;
import com.dongge.Entity.UserMapperI;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * Created by zhudong on 2016/10/7.
 */
public class TestMybatis {

    private SqlSession session;

    @Before
    public void init(){
        String resource = "conf.xml";
        //使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）
        InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）
        //Reader reader = Resources.getResourceAsReader(resource);
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        session = sessionFactory.openSession();
        /**
         * 映射sql的标识字符串，
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值，
         * getUser是select标签的id属性值，通过select标签的id属性值就可以找到要执行的SQL
         */
//        String statement = "com.dongge.Entity.userMapper.getUser";//映射sql的标识字符串
//        //执行查询返回一个唯一user对象的sql
//        User user = session.selectOne(statement, 1);
//        System.out.println(user);
    }

    @Test
    public void addUser(){
        String statement = "com.dongge.Entity.userMapper.addUser";
        User user = new User();
        user.setName("孤独求败");
        user.setAge(12);
        session.insert(statement,user);
    }

    @Test
    public void getAllUsers(){
        String statement = "com.dongge.Entity.userMapper.getAllUsers";
        List<User>  users = session.selectList(statement);
        for(User user:users){
            System.out.println(user);
        }
    }

    @Test
    public void testGetUser(){
        String statement = "com.dongge.Entity.userMapper.getUser";
        User user = session.selectOne(statement,1);
        System.out.println(user);
    }

    @Test
    public void delete(){
        String statement = "com.dongge.Entity.userMapper.deleteUser";
        session.delete(statement,1);
    }

    @Test
    public void getAllUsersByAnnotation(){
        UserMapperI mapper = session.getMapper(UserMapperI.class);
        List<User> users = mapper.getAll();
        for(User user:users){
            System.out.println(user);
        }
    }


}
